<template>
  <view class="page">
    <!-- 导航栏 -->
    <tui-navigation-bar title="订单确认"></tui-navigation-bar>

    <section class="header">
      <view class="row">
        <view>门店</view>
        <view class="font-weight-bold">{{ loginInfo.bname }}</view>
      </view>
      <view class="row">
        <view>房台</view>
        <view class="font-weight-bold">{{ currentRoomShopCart.roomid }}</view>
      </view>
      <view class="row" style="margin-bottom: 10px">
        <view>备注</view>
        <view style="color: #6a78a3">限制15字以内</view>
      </view>
      <input v-model="remark" type="text" length="15" placeholder="请输入备注，选填" class="input-remark" placeholder-class="input-remark-placeholder" />
    </section>

    <view class="section-title">已选商品明细</view>
    <section class="cart-container">
      <block v-for="rowData in currentShopCart" :key="rowData.id">
        <view class="good-item item">
          <!-- {{ isMeal(rowData.set) ? '套餐：' : '' }} -->
          <view class="column-1"> {{ rowData.name }}</view>
          <view class="column-2">
            x{{ rowData.selectNumber }}
            <view class="tag-box"></view>
          </view>
          <view class="column-3 text-price">{{ rowData.Price }}</view>
        </view>

        <block v-if="isMeal(rowData.set) && rowData.mealForm && rowData.mealForm.length > 0">
          <view v-for="item in rowData.mealForm" :key="item.setinfoid" class="meal-form item">
            <view class="column-1">{{ item.goodsname }} </view>
            <view class="column-2">
              <view>x{{ item.selectNumber }}</view>
              <view class="tag-box">
                <tui-tag padding="4px 5px" width="100%" size="20rpx" type="gold" plain>赠送</tui-tag>
              </view>
            </view>
            <view class="column-3">{{ item.Price }}</view>
          </view>
        </block>

        <!-- 例送 -->
        <view v-if="rowData.lsNumber" class="good-item item">
          <!-- {{ isMeal(rowData.set) ? '套餐：' : '' }} -->
          <view class="column-1">{{ rowData.name }}</view>
          <view class="column-2">
            <view>x{{ rowData.lsNumber }}</view>
            <view class="tag-box">
              <tui-tag padding="4px 5px" width="100%" size="20rpx" type="gold" plain>例送</tui-tag>
            </view>
          </view>
          <view class="column-3"></view>
        </view>
      </block>
    </section>

    <view class="section-title">支付方式</view>
    <section class="pay-type-container">
      <radio-group @change="radioChange">
        <view class="pay-type-item">
          <view class="is-flex items-center">
            <my-icon name="wxpay" color="#4fae70" size="24"></my-icon>
            <view class="ml-10">微信支付</view>
          </view>
          <view>
            <radio color="#edd2b2" value="wxPay" :checked="checkedPayType === 'wxPay'"></radio>
          </view>
        </view>

        <view class="pay-type-item">
          <view class="is-flex items-center">
            <my-icon name="vip" color="gold" size="24"></my-icon>
            <view class="ml-10">会员支付</view>
          </view>
          <view>
            <radio color="#edd2b2" value="vipPay" :checked="checkedPayType === 'vipPay'"></radio>
          </view>
        </view>
      </radio-group>
    </section>

    <!-- 底部统计 + 支付栏 -->
    <view class="foot-height"></view>
    <view class="foot">
      <view class="foot-left">
        <view class="price-box">
          <text>合计 ： </text>
          <text class="text-price font-weight-bold">{{ currentRoomShopCart.totalPrice }}</text>
        </view>
      </view>

      <view class="foot-btn foot-center" @click="$msg('text', '暂不支持该支付方式')">
        <text>找人付</text>
      </view>
      <view class="foot-btn foot-right" @click="orderPay()">
        <text>付款</text>
      </view>
    </view>
  </view>
</template>

<script>
import Utils from '@/utils/index'
import common from '@/pages/shop/mixins/common'
export default {
  mixins: [common],
  data() {
    return {
      // 当前房台购物车对象 (房台 + 购物车)
      currentRoomShopCart: null,
      // 当前房台购物车数组 （仅购物车）
      currentShopCart: null,
      // 默认选中的支付方式
      checkedPayType: 'wxPay',
      // 备注
      remark: '',
      // 计算付款金额返回的数据
      orderPayInfo: null,
      // 是否正在请求接口
      requestOrderPay: false
    }
  },
  computed: {
    loginIngo() {
      return this.$store.getters.loginInfo
    }
  },
  onLoad(options) {},
  onShow() {
    this.init()
    this.getOrderPayMoney()
  },
  methods: {
    /**
     * 初始化购物车对象 和 购物车数组数据
     */
    init() {
      let { allCarts, currentRoomShopCart, currentShopCart } = this.getCurrentRoomShopCart()
      this.currentRoomShopCart = currentRoomShopCart
      this.currentShopCart = currentShopCart

      if (!this.currentRoomShopCart) {
        this.$msg('text', '数据异常')
        return uni.navigateBack()
      }
    },
    /**
     * 计算付款金额
     * 应用场景 ： 需要在点击付款前调用
     * 主要用于后台计算某些应用场景的打折等、与前端关系不大。但如果后台返回错误，需要禁止点击付款按钮
     */
    getOrderPayMoney() {
      const orderInfo = this.computedOrderInfo()
      const orderInfoLength = this.$format(orderInfo, 'length') > 0
      if (!orderInfoLength) return this.$msg('text', '订单数据异常')

      return new Promise(async (resolve, reject) => {
        const baseParam = this.getBase(['token', 'usertoken', 'selectuniacid', 'bid', 'ordernum'])
        if (!baseParam) return reject()

        Object.assign(baseParam, { orderinfo: orderInfo })
        this.$api
          .getOrderPayMoney(baseParam)
          .then(res => {
            console.res('计算付款金额', res)
            this.orderPayInfo = this.$format(res, 'data')
          })
          .catch(err => {
            console.err('计算付款金额', err)
            this.errMsg(err, '计算付款金额异常')
          })
      })
    },
    /**
     * 扫码点单支付下单
     */
    orderPay: Utils.debounce(function () {
      if (this.requestOrderPay) return console.log('正在请求中')

      if (this.checkedPayType === 'vipPay') {
        return this.$msg('text', '暂不支持该支付方式')
      }

      // 计算付款金额返回的数据
      const orderPayInfo = this.orderPayInfo
      if (this.$isEmpty(orderPayInfo)) return this.getOrderPayMoney()

      // 订单数据
      const orderInfo = this.computedOrderInfo()

      return new Promise(async (resolve, reject) => {
        const baseParam = this.getBase(['token', 'usertoken', 'roomid', 'selectuniacid', 'bid', 'ordernum'])
        if (!baseParam) return reject()

        const currentRoomShopCart = this.currentRoomShopCart
        if (this.$utils.isNumber(currentRoomShopCart.totalPrice)) {
          Object.assign(baseParam, {
            orderinfo: orderInfo,
            totalmoney: currentRoomShopCart.totalPrice,
            prepayid: this.$format(orderPayInfo, 'prepayid'),
            childorderid: this.$format(orderPayInfo, 'childorderid')
          })
        } else {
          return this.$msg('text', '支付总金额异常')
        }

        if (this.remark) {
          Object.assign(baseParam, { remark: this.remark })
        }

        console.param('扫码点单支付下单', baseParam)

        try {
          this.requestOrderPay = true
          const res = await this.$api.orderPay(baseParam)
          this.requestOrderPay = false

          console.res('扫码点单支付下单', res)
          this.wxPay(this.$format(res, 'data')).then(res => {
            setTimeout(() => {
              this.$open('/shop/shop', 'rt', { clearShopCart: true })
            }, 1500)
          })
        } catch (err) {
          this.requestOrderPay = false
          console.err('扫码点单支付下单', err)
          this.$msg('text', '提交订单失败')
          reject(err)
        }
      })
    }, 2000),
    // 计算购物车的订单数据 - 适配生成扫码订单支付接口所需的数据结构
    computedOrderInfo() {
      const orderInfo = this.currentShopCart.reduce((pre, rowData) => {
        // 主套餐
        const info = { BeverageID: rowData.goodsid || rowData.id, Number: rowData.selectNumber, Set: '0', Give: '0' }
        pre.push(info)

        // 单品 - 例送
        if (!this.isMeal(rowData.set)) {
          if (rowData.lsNumber > 0) {
            const singleLsInfo = { BeverageID: rowData.id, Number: rowData.lsNumber, Set: '0', Give: '2' }
            pre.push(singleLsInfo)
          }
        }

        // 套餐
        if (this.isMeal(rowData.set)) {
          // 配送
          const mealForm = this.$format(rowData, 'mealForm')
          if (!mealForm || mealForm.length === 0) return
          mealForm.forEach(item => {
            const mealFormInfo = { BeverageID: item.setinfoid, Number: item.selectNumber, Set: '1', Give: '1' }
            pre.push(mealFormInfo)
          })

          // 例送
          if (rowData.lsNumber > 0) {
            const mealFormLsInfo = { BeverageID: rowData.id, Number: rowData.lsNumber, Set: '0', Give: '2' }
            pre.push(mealFormLsInfo)
          }
        }
        return pre
      }, [])

      return JSON.stringify(orderInfo)
    },

    radioChange(e) {
      this.checkedPayType = e.detail.value
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.page {
  color: $color-primary-grey-text;
}

$paddingX: 15px;
.header {
  padding: 20px $paddingX;
  background: $color-primary-modal-bg;
  .row {
    @include is-flex(row, space-between, center, nowrap);
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    view:first-child {
      color: $color-primary-grey-text;
    }
  }
  .input-remark {
    border-radius: 2px;
    background: #282f47;
    height: 43px;
    line-height: 43px;
    padding: 0 10px;
  }
  ::v-deep .input-remark-placeholder {
    color: #6a78a3;
  }
}

// 已选商品
.cart-container {
  background: $color-primary-modal-bg;
  font-size: $font-size-xs;
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px $paddingX;
    &:nth-child(even) {
      background: #292f45;
    }
    .column-1 {
      width: 50%;
      text-align: left;
      padding-right: 20px;
    }
    .column-2 {
      width: 25%;
      text-align: left;
      @include is-flex(row, flex-end, center, wrap);
      .tag-box {
        width: 30px;
        margin-left: 4px;
        ::v-deep .tui-tag {
          white-space: nowrap;
        }
      }
    }
    .column-3 {
      width: 25%;
      text-align: right;
      color: $gold;
    }
  }
}

// 支付方式
.pay-type-container {
  padding: 15px $paddingX;
  background: $color-primary-modal-bg;
  .pay-type-item {
    @include is-flex(row, space-between, center, nowrap);
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

$footerBg: #2b3249;
$footerHeight: 60px;
.foot-height {
  height: calc(100px + #{$footerHeight});
}

.foot {
  position: fixed;
  bottom: 0px;
  left: 0;
  right: 0;

  z-index: 11;
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow: hidden;

  height: $footerHeight;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.4);
  background: $footerBg;

  .foot-left {
    padding: 0 12px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
    .price-box {
      display: flex;
      flex-direction: row;
      align-items: baseline;
      margin-left: 5px;
      .text-price {
        color: $gold;
        font-size: 18px;
      }
    }
  }

  .foot-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    // font-weight: bold;
    border-radius: 10px;
    height: 80%;
    width: 25vw;
    margin-right: 10px;
    transition: all 0.3s;
  }

  .foot-center {
    background: linear-gradient(180deg, #464e69, #20273d);
    color: $color-primary-title;
    &:active {
      background: linear-gradient(180deg, #414a66, #19213b);
    }
  }

  .foot-right {
    background: linear-gradient(180deg, #ffedcb, #f1c99a);
    color: $color-primary-bg;
    &:active {
      background: linear-gradient(45deg, #ffe5b6, #f3c188);
    }
  }
}
</style>
